﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Xml;
using System.Data;

public partial class Controls_ImageGallery : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            btnAddAlbum.CommandName = "insert";
            btnCategoryAdd.CommandName = "insert";
            LoadAlbum();

            //Load Categories
            rptDanhMuc.DataSource = dmsFunction.GetAlbumCategories();
            rptDanhMuc.DataBind();

            ddldanhmuc.Items.Add(new ListItem("Không có danh mục", "0"));
            foreach (DataRow item in dmsFunction.GetAlbumCategories().AsEnumerable())
            {
                ddldanhmuc.Items.Add(new ListItem(item["Title"].ToString(),item["CateID"].ToString()));
            }
        }
    }

    protected void LoadAlbum()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("id");
        dt.Columns.Add("title");
        dt.Columns.Add("imageurl");
        dt.Columns.Add("description");
        dt.Columns.Add("order", typeof(Int32));
        dt.Columns.Add("Category");

        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath+"dms/dmsAlbums.xml"));
        XmlNodeList nodelist = xmldoc.SelectNodes("dms/album");
        foreach (XmlNode item in nodelist)
        {
            if (item["lock"].InnerText=="0")
            {
                DataRow dr = dt.NewRow();
                dr[0] = item.Attributes["id"].Value;
                dr[1] = item["title"].InnerText;
                dr[2] = item["poster"].InnerText;
                dr[3] = item["description"].InnerText;
                dr[4] = item["order"].InnerText;
                XmlDocument xmldoc11 = new XmlDocument();
                xmldoc11.Load(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/dmsAlbumCategory.xml"));
                XmlNode xNode = xmldoc11.SelectSingleNode("dms/category[@id='" + item.Attributes["category"].Value
 + "']");
                if (xNode!=null)
                {
                    dr[5] = xNode["title"].InnerText;
                }
                else
                {
                    dr[5] = "Không có danh mục";
                }
                
                dt.Rows.Add(dr);
            }
           
        }
        DataTable data = new DataTable();
        DataTable tblEmployees = dt;
        DataView dv = tblEmployees.DefaultView;
        dv.Sort = "order ASC";
        data = dv.ToTable();
        dtlAlbums.DataSource = data;
        dtlAlbums.DataBind();
    }

    void ClearForm()
    {
        Image1.ImageUrl = "";
        txtmota.Text = txtmota_en.Text = "";
        txttenalbum.Text = txttenalbum_en.Text = "";
        btnAddAlbum.CommandName = "insert";
    }

    public string countImageInAlbum(string AlbumID)
    {
        int count = 0;
        //XmlDocument xmldoc = new XmlDocument();
        //xmldoc.Load(Server.MapPath("~/dms/dmsAlbums.xml"));

        //XmlNode xNode = xmldoc.SelectSingleNode("dms/album[@id='" + AlbumID + "']");
        XmlDocument xmldoc1 = new XmlDocument();
        xmldoc1.Load(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath+"dms/dmsImages.xml"));
        XmlNodeList nodelist = xmldoc1.SelectNodes("dms/image[@albumid='" + AlbumID + "']");
        foreach (XmlNode item in nodelist)
        {
            if (item.Attributes["albumid"].Value == AlbumID)
            {
                count++;
            }
        }
        return count.ToString();
    }

    protected void lnkEdit_Command(object sender, CommandEventArgs e)
    {
        int ID = int.Parse(e.CommandArgument.ToString());
        XmlDocument xmldoc1 = new XmlDocument();
        xmldoc1.Load(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath+"dms/dmsAlbums.xml"));
        //XmlNodeList nodelist = xmldoc1.SelectNodes("dms/album");
        XmlNode xNode = xmldoc1.SelectSingleNode("dms/album[@id='" + ID + "']");
        if (xNode != null)
        {
            Image1.ImageUrl = KTFrameworkCus.Globals.ApplicationPath+"dms/Albums/" + xNode["poster"].InnerText;
            txtmota.Text = xNode["description"].InnerText;
            txttenalbum.Text = xNode["title"].InnerText;
            txtmota_en.Text = xNode["description_en"].InnerText;
            txttenalbum_en.Text = xNode["title_en"].InnerText;
            HiddenField1.Value = xNode["poster"].InnerText;
            ddldanhmuc.SelectedValue = xNode.Attributes["category"].Value;
            btnAddAlbum.CommandName = "edit";
            btnAddAlbum.CommandArgument = ID.ToString();
            btnAddAlbum.Text = "Cập nhập";
            btnCancel.Visible = true;
        }

        //LoadSupporterDetails(ID);
    }

    protected void lnkDelete_Command(object sender, CommandEventArgs e)
    {
        int ID = int.Parse(e.CommandArgument.ToString());
        XmlDocument xmldoc1 = new XmlDocument();
        xmldoc1.Load(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath+"dms/dmsAlbums.xml"));
        XmlNode xNode = xmldoc1.SelectSingleNode("dms/album[@id='" + ID + "']");
        if (xNode != null)
        {
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath+"dms/dmsImages.xml"));
            XmlNodeList nodelist = xmldoc.SelectNodes("dms/image[@albumid='" + ID + "']");
            if (nodelist.Count > 0)
            {
                foreach (XmlNode item in nodelist)
                {
                    item.ParentNode.RemoveChild(item);
                    xmldoc.Save(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath+"dms/dmsImages.xml"));
                    dmsFunction.deleteImage(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/Images/f/" + item["fullimage"].InnerText));
                    dmsFunction.deleteImage(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/Images/t/" + item["thumbimage"].InnerText));
                }
            }
            xNode.ParentNode.RemoveChild(xNode);
            if (xNode["poster"].InnerText!="noimage.gif")
            {
                dmsFunction.deleteImage(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/Albums/" + xNode["poster"].InnerText));
            }
           
            xmldoc1.Save(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath+"dms/dmsAlbums.xml"));
            LoadAlbum();
        }
        //LoadSupporterDetails(ID);
    }

    protected void lnkCategoryEdit_Command(object sender, CommandEventArgs e) {

        int ID = int.Parse(e.CommandArgument.ToString());
        XmlDocument xmldoc1 = new XmlDocument();
        xmldoc1.Load(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/dmsAlbumCategory.xml"));
        //XmlNodeList nodelist = xmldoc1.SelectNodes("dms/album");
        XmlNode xNode = xmldoc1.SelectSingleNode("dms/category[@id='" + ID + "']");
        if (xNode != null)
        {
            
            txttitle.Text = xNode["title"].InnerText;
            txttitle_en.Text = xNode["title_en"].InnerText;
            txtthutu.Text = xNode["order"].InnerText;
            
            btnCategoryAdd.CommandName = "edit";
            btnCategoryAdd.CommandArgument = ID.ToString();
            btnCategoryAdd.Text = "Cập nhập";
            btnCategoryCancel.Visible = true;
        }
    }
    protected void lnkCategoryDelete_Command(object sender, CommandEventArgs e) {
        int ID = int.Parse(e.CommandArgument.ToString());
        XmlDocument xmldoc1 = new XmlDocument();
        xmldoc1.Load(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/dmsAlbumCategory.xml"));
        XmlNode xNode = xmldoc1.SelectSingleNode("dms/category[@id='" + ID + "']");
        if (xNode != null)
        {
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/dmsAlbums.xml"));
            XmlNodeList nodelist = xmldoc.SelectNodes("dms/album[@category='" + ID + "']");
            if (nodelist.Count > 0)
            {
                foreach (XmlNode item in nodelist)
                {
                    item.Attributes["category"].Value = "0";
                    xmldoc.Save(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/dmsAlbums.xml")); 
                }
            }
            xNode.ParentNode.RemoveChild(xNode);

            xmldoc1.Save(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/dmsAlbumCategory.xml"));

            Response.Redirect(Request.RawUrl);
        }
    }
    protected void btnAddAlbum_Click(object sender, EventArgs e)
    {
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath+"dms/dmsAlbums.xml"));

        if (btnAddAlbum.CommandName == "insert")
        {
            XmlNodeList nodelist = xmldoc.SelectNodes("dms/album");
            string latestNodeID = "";

            int MessageID = 0;

            if (nodelist.Count == 0)
            {
                MessageID = 1;

            }
            else
            {
                XmlNode node = nodelist.Item(nodelist.Count - 1);
                if (node == null)
                {
                    latestNodeID = "1";
                    MessageID = int.Parse(latestNodeID) + 1;
                }
                else
                {
                    latestNodeID = node.Attributes["id"].Value;
                    MessageID = int.Parse(latestNodeID) + 1;
                }
            }
            XmlNode newNode = xmldoc.CreateNode(XmlNodeType.Element, "album", null);
            XmlAttribute xmla = xmldoc.CreateAttribute("id");
            xmla.Value = MessageID.ToString();
            newNode.Attributes.Append(xmla);

            XmlAttribute xmlac = xmldoc.CreateAttribute("category");
            xmlac.Value = ddldanhmuc.SelectedValue;
            newNode.Attributes.Append(xmlac);


            XmlNode nodeTitle = xmldoc.CreateElement("title");
            nodeTitle.InnerText = txttenalbum.Text;
            XmlNode nodeDescription = xmldoc.CreateElement("description");
            nodeDescription.InnerText = txtmota.Text;
            XmlNode nodeTitle_en = xmldoc.CreateElement("title_en");
            nodeTitle_en.InnerText = txttenalbum_en.Text;
            XmlNode nodeDescription_en = xmldoc.CreateElement("description_en");
            nodeDescription_en.InnerText = txtmota_en.Text;
            XmlNode nodeImageUrl = xmldoc.CreateElement("poster");
            nodeImageUrl.InnerText = Photo_Upload();
            XmlNode nodeAddedDate = xmldoc.CreateElement("addedDate");
            nodeAddedDate.InnerText = DateTime.Now.ToString();
            XmlNode nodeModifiedDate = xmldoc.CreateElement("modifiedDate");
            nodeModifiedDate.InnerText = DateTime.Now.ToString();
            XmlNode nodeOrder = xmldoc.CreateElement("order");
            nodeOrder.InnerText = (MessageID + 1).ToString();

            XmlNode nodeLock = xmldoc.CreateElement("lock");
            nodeLock.InnerText = "0";

            newNode.AppendChild(nodeTitle);
            newNode.AppendChild(nodeDescription);
            newNode.AppendChild(nodeTitle_en);
            newNode.AppendChild(nodeDescription_en);
            newNode.AppendChild(nodeImageUrl);
            newNode.AppendChild(nodeAddedDate);
            newNode.AppendChild(nodeModifiedDate);
            newNode.AppendChild(nodeOrder);
            newNode.AppendChild(nodeLock);
           
            xmldoc.DocumentElement.AppendChild(newNode);
        }
        else
        {

            XmlNodeList nodelist = xmldoc.SelectNodes("dms/album");
            foreach (XmlNode item in nodelist)
            {
                string id = item.Attributes["id"].Value;
                if (id == btnAddAlbum.CommandArgument)
                {
                    item["title"].InnerText = txttenalbum.Text;
                    item["title_en"].InnerText = txttenalbum_en.Text;
                    item["description"].InnerText = txtmota.Text;
                    item["description_en"].InnerText = txtmota_en.Text;
                    item["poster"].InnerText = Photo_Upload();
                    item["modifiedDate"].InnerText = DateTime.Now.ToString();
                    item.Attributes["category"].Value = ddldanhmuc.SelectedValue;
                    btnAddAlbum.CommandName = "insert";
                    btnAddAlbum.Text = "Thêm mới";
                    break;
                }
            }
        }


        xmldoc.Save(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath+"dms/dmsAlbums.xml"));
        ClearForm();
        LoadAlbum();
    }

    protected string Photo_Upload()
    {
        string strFileName = "";
        // kiem tra xem user co chon hinh dai dien ko
        if (PhotoFile.HasFile)
        {
            // kiem tra phan mo rong cua file co hop le hay khong
            string strExtension = System.IO.Path.GetExtension(PhotoFile.FileName).ToUpper();
            if (strExtension == ".JPG" || strExtension == ".JPEG" || strExtension == ".PNG")
            {
                // lay ten file de khong bi trung file + phan mo rong cua file can upload
                strFileName = DateTime.Now.Ticks + System.IO.Path.GetExtension(PhotoFile.FileName);

                //duong dan tao save file Large
                string strFilePathLarge = KTFrameworkCus.Globals.ApplicationPath + "dms/Albums/" + strFileName;

                PhotoFile.PostedFile.SaveAs(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath+"dms\\Albums\\" + strFileName));
                Bitmap bmp = new Bitmap(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath+"dms/Albums/" + strFileName));
                float imgW = bmp.Width;
                float imgH = bmp.Height;
                float ratio = imgW / imgH;

                int fW = 300;
                int fH = (int)Math.Ceiling(300 / ratio);

                if (fH < 200)
                {
                    fH = 200;
                    fW = (int)Math.Ceiling(200 * ratio);
                }
                bmp.Dispose();
                resizeImage(KTFrameworkCus.Globals.ApplicationPath+"dms/Albums/" + strFileName, fW, fH);

            }
            else
            {
                return strFileName = "";
            }
        }
        else
        {
            if (btnAddAlbum.CommandName == "insert")
            {
                return "noimage.gif";
            }
            else
            {
                return HiddenField1.Value.Trim();
            }

        }

        return strFileName;
    }

    public Size OriginalImageSize { get; set; }
    public Size NewImageSize { get; set; }
    protected void resizeImage(string imageUrl, int FixedWidth, int FixedHeight)
    {       
        Bitmap imgPhoto = new Bitmap(Server.MapPath(imageUrl));
      
        Bitmap b = new Bitmap(FixedWidth, FixedHeight);
        
        Graphics g = Graphics.FromImage(b);
        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.DrawImage(imgPhoto, 0, 0, FixedWidth, FixedHeight);
        
        imgPhoto.Dispose();
        b.Save(Server.MapPath(imageUrl), ImageFormat.Png);
        b.Dispose();
      
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        ClearForm();
        btnAddAlbum.CommandName = "insert";
        btnAddAlbum.CommandArgument = "";
        btnAddAlbum.Text = "Thêm mới";
        btnCancel.Visible = false;
    }

    protected void btnCategoryAdd_Click(object sender, EventArgs e)
    {
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/dmsAlbumCategory.xml"));

        if (btnCategoryAdd.CommandName == "insert")
        {
            XmlNodeList nodelist = xmldoc.SelectNodes("dms/category");
            string latestNodeID = "";

            int MessageID = 0;

            if (nodelist.Count == 0)
            {
                MessageID = 1;

            }
            else
            {
                XmlNode node = nodelist.Item(nodelist.Count - 1);
                if (node == null)
                {
                    latestNodeID = "1";
                    MessageID = int.Parse(latestNodeID) + 1;
                }
                else
                {
                    latestNodeID = node.Attributes["id"].Value;
                    MessageID = int.Parse(latestNodeID) + 1;
                }
            }
            XmlNode newNode = xmldoc.CreateNode(XmlNodeType.Element, "category", null);
            XmlAttribute xmla = xmldoc.CreateAttribute("id");
            xmla.Value = MessageID.ToString();
            newNode.Attributes.Append(xmla);

            XmlNode nodeTitle = xmldoc.CreateElement("title");
            nodeTitle.InnerText = txttitle.Text;            
            XmlNode nodeTitle_en = xmldoc.CreateElement("title_en");
            nodeTitle_en.InnerText = txttitle_en.Text;
            XmlNode nodeorder = xmldoc.CreateElement("order");
            nodeorder.InnerText = (int.Parse("0"+txtthutu.Text)).ToString();

            newNode.AppendChild(nodeTitle);
            newNode.AppendChild(nodeTitle_en);
            newNode.AppendChild(nodeorder);          

            xmldoc.DocumentElement.AppendChild(newNode);
        }
        else
        {

            XmlNodeList nodelist = xmldoc.SelectNodes("dms/category");
            foreach (XmlNode item in nodelist)
            {
                string id = item.Attributes["id"].Value;
                if (id == btnCategoryAdd.CommandArgument)
                {
                    item["title"].InnerText = txttitle.Text;
                    item["title_en"].InnerText = txttitle_en.Text;
                    item["order"].InnerText = (int.Parse("0" + txtthutu.Text)).ToString();
                    btnCategoryAdd.CommandName = "insert";
                    btnCategoryAdd.Text = "Thêm mới";
                    break;
                }
            }
        }


        xmldoc.Save(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/dmsAlbumCategory.xml"));
        Response.Redirect(Request.RawUrl);
        
    }
    protected void btnCategoryCancel_Click(object sender, EventArgs e)
    {
        ClearForm1();
        btnCategoryAdd.CommandName = "insert";
        btnCategoryAdd.CommandArgument = "";
        btnCategoryAdd.Text = "Thêm mới";
        btnCategoryCancel.Visible = false;
    }

    void ClearForm1()
    {   
        txttitle.Text = txttitle_en.Text = txtthutu.Text = "";
        btnCategoryAdd.CommandName = "insert";
    }
}